package sg.edu.ntu.metaweb.pastry;

import rice.p2p.commonapi.Message;
import sg.edu.ntu.metaweb.http.RequestHandler;
import sg.edu.ntu.metaweb.pastry.messages.RequestRateWebpageMessage;
import sg.edu.ntu.metaweb.pastry.messages.RequestWebpageDataMessage;
import sg.edu.ntu.metaweb.pastry.messages.ResponseRateWebpageMessage;
import sg.edu.ntu.metaweb.pastry.messages.ResponseWebpageDataMessage;

public class MessageHandler {

	private PastryNodeHandle pastryNodeHandle;
	
	public MessageHandler(PastryNodeHandle pastryNodeHandle) {
		this.pastryNodeHandle = pastryNodeHandle;
	}
	
	public void handleMessage(Message msg) {
		
		if (msg instanceof RequestRateWebpageMessage) {
			System.out.println("Handle <RequestRateWebpageMessage>");
			RequestRateWebpageMessage castMsg = (RequestRateWebpageMessage)msg;
			this.pastryNodeHandle.storageManager.requestRateWebpage(castMsg);
		}
		else if (msg instanceof RequestWebpageDataMessage) {
			System.out.println("Handle <RequestWebpageDataMessage>");
			RequestWebpageDataMessage castMsg = (RequestWebpageDataMessage)msg;
			this.pastryNodeHandle.storageManager.requestWebpageData(castMsg);
		}
		else if (msg instanceof ResponseWebpageDataMessage) {
			System.out.println("Handle <ResponseWebpageDataMessage>");
			ResponseWebpageDataMessage castMsg = (ResponseWebpageDataMessage)msg;
			sendXMLResponse(castMsg.getRequestID(), castMsg.getWebpageData());
		}
		else if (msg instanceof ResponseRateWebpageMessage) {
			System.out.println("Handle <ResponseRateWebpageMessage>");
			ResponseRateWebpageMessage castMsg = (ResponseRateWebpageMessage)msg;
			sendXMLResponse(castMsg.getRequestID(), castMsg.getResponse());
		}
		else {
			System.out.println("Unsupported message type.");
		}
		
	}
	
	
	private void sendXMLResponse(int requestID, String xmlString) {
		RequestHandler requestHandler = pastryNodeHandle.httpConnectionManager.popRequestHandler(requestID);
		
		if (requestHandler != null) {
			requestHandler.write(xmlString);
		}
		else
			System.out.println("[MessageHandler] no RequestHandler found.");
	}

}
